<template>
  <div class="article-list">
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :success-text="successText">
    <!-- 列表 -->
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
       v-model:error="error"
        error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
    <!-- 内容 -->
  <ArticleItem v-for="item in list" :key="item.id" :article="item"></ArticleItem>
</van-list>
</van-pull-refresh>
  </div>
</template>

<script>
import { ref } from 'vue'
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item/index.vue'
export default {
  name: 'ArticleList',
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  components: { ArticleItem },
  setup (props) {
    const list = ref([])
    const loading = ref(false)// 加载
    const finished = ref(false)// 加载完毕
    const timestamp = ref(null)// 页码
    const error = ref(false)// 加载失败
    const isLoading = ref(false)// 下拉刷新
    const successText = ref('刷新成功')// 下拉刷新成功提示文本
    const onLoad = async () => {
      try {
        // 异步更新数据
        const { data } = await getArticles({
          channel_id: props.channel.id, // 频道id
          timestamp: timestamp.value || Date.now()// 时间戳(页码)
        })
        const { results } = data.data
        list.value.push(...results)

        // 加载状态结束
        loading.value = false

        // 数据全部加载完成
        if (results.length === 0) {
          finished.value = true
        } else {
        // 更新下一页数据的时间戳
          timestamp.value = data.data.pre_timestamp
        }
      } catch (err) {
        error.value = true
        loading.value = false
      }
    }
    // 下拉刷新
    async function onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: props.channel.id, // 频道id
          timestamp: Date.now()// 时间戳(页码)
        })
        const { results } = data.data
        list.value.unshift(...results)
        isLoading.value = false
        successText.value = `刷新成功，更新了${results.length}条数据`
      } catch (err) {
        successText.value = '刷新失败'
        isLoading.value = false
      }
    }
    return {
      list,
      onLoad,
      loading,
      finished,
      error,
      isLoading,
      onRefresh,
      successText
    }
  }
}
</script>

<style lang='less' scoped>
// 记住列表的滚动位置
.article-list {
  height: 79vh;// 1vh单位是指可视区域高度的1/100
  overflow-y: auto;
}
</style>
